# coding=utf-8
import requests, os, re
from ddt import ddt, data
import unittest
from common.common_request import PublicRequest
from common.readData import read_excel
from common.readConfig import read
from common.caseLog import Log
from common.create_time import time_create
import json, ast
import time
from requests.adapters import HTTPAdapter
from random import randint
import pytest



@ddt
class MsgTestCase(unittest.TestCase):

    BASH_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    file_name = read("case_data", 'file_name')
    file_path = os.path.join(os.path.join(BASH_DIR, file_name))
    datass =read_excel(file_path, 'Sheet4')
    log = Log()
    r = requests.session()

    @classmethod
    def setUpClass(cls):
        cls.log.info('测试开始')
        cls.host = read('host', 'message_host_test')
        cls.host_mysql = read('mysql_pre', 'host')
        cls.port = int(read('mysql_pre', 'port'))
        cls.user = read('mysql_pre', 'user')
        cls.password = read('mysql_pre', 'password')
        cls.db = read('mysql_pre', 'db')
        # cls.token = cls.__login()


    @classmethod
    def tearDownClass(cls):

        cls.log.info('测试结束')

    @classmethod
    def __login(cls, tenant='-1'):
        h = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36",
            "TENANT-ID": "-1",
        }
        username = read('rule_user', 'username')
        password = read('rule_user', 'password')
        cls.log.info(username)
        cls.log.info(password)
        api = "/api/upms/auth/login"
        json_data = {
            "grant_type": "password",
            "username": username,
            "password": password,
            "tenant": tenant,
            "scope": "web",
            "authorization": "cG9ydGFsLWNsaWVudDpiNGZHOHRNQA=="
        }
        result = requests.post(cls.host + api, headers=h, json=json_data).json()
        cls.log.info(result)
        access = re.search(r"access_token': '(.+)', 'token_type", repr(result))
        access_token = access.group(1)
        cls.log.info(access_token)
        token = re.search(r"token_type': '(.+)', 'refresh_", repr(result))
        token_type = token.group(1)
        cls.log.info(token_type)
        return access_token

    def assertTrue(self, expr, str_a, str_b, msg=None):
        """Check that the expression is true."""
        if not expr:
            msg = self._formatMessage(msg, "%s <h3 style=color:red> 不属于 </h3> %s" % (repr(str_a), repr(str_b)))
            raise self.failureException(msg)

    def assertMy(self, str_one, str_two):
        try:
            response = json.loads(str_one)
            str_a = str(response)
            str_b = str(str_two)
            str_c = str(response['code'])
            str_d = str(str_two['code'])
            if str_a == str_b:
                result = True
            elif str_c == str_d:
                result = True
            # elif str_a[:-1] in str_b:
            #     result = True
            else:
                result = False
            self.assertTrue(result, str_a, str_b)
        except Exception:
            str_a = str(str_one)
            str_b = str(str_two)
            if str_a in str_b:
                result = True
            else:
                result = False
            self.assertTrue(result, str_a, str_b)


    @data(*datass)
    def testCase(self, datas):

        self._testMethodDoc = datas['case_name']  # 继承自unittest.TestCase，然后重写self._testMethodDoc
        self.log.debug("执行测试用例%s" % datas['case_name'])
        p_request = PublicRequest(host=self.host_mysql, user=self.user, password=self.password, db=self.db)
        result = p_request.publicSend(self.host, method=datas['method'], api=datas['api'], token=self.__login(),
                                      auth=datas['Authorization'], data_parameter=datas['data_parameter'],
                                      url_parameter=datas['url_parameter'], data=datas['data'],
                                      sql=datas['sql'], data_time=datas['data_time'], url_time=datas['url_time'],
                                      code_only=datas['code_only'], api_code_only=datas['api_code_only'],
                                      variable=datas['variable'], get_variable=datas['get_variable']).json()
        self.log.debug(result)
        self.assertMy(datas['response'], result)


if __name__ == '__main__':
    unittest.main()
